package fr.upmc.cie;

import fr.upmc.cie.data.DataManager;
import fr.upmc.cie.data.TicketItem;
import fr.upmc.cie.ext.RemoteImageGetter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.ViewFlipper;

public class TicketDisplay extends Activity implements OnGestureListener {


	private TicketDisplay self = this;
	
	private GestureDetector detector;  
	private ViewFlipper flipper;
	private TicketItem ticket;
	private ToggleButton archiver;
	private RatingBar rating;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.ticket_display);
		flipper = (ViewFlipper) this.findViewById(R.id.ViewFlipper01); 
		
		detector = new GestureDetector(this);  
	
		//Rating bar
		rating = (RatingBar) this.findViewById(R.id.td_rating);
		
		rating.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){

			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {
				ticket.setRating(ratingBar.getRating());
				if (DataManager.getTicketManager(self).isTicketArchived(ticket)){
					DataManager.getTicketManager(self).updateTicket(ticket);
				}
			}
			
		});
		
		//Bouton archiver
		archiver = (ToggleButton) this.findViewById(R.id.td_archive);
		archiver.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				//Verifier l'action de archiver/desarchiver un ticket
				if (archiver.isChecked()){
					if (!DataManager.getTicketManager(self).isTicketArchived(ticket)){
						DataManager.getTicketManager(self).archiverTicket(ticket);
						rating.setVisibility(View.VISIBLE);
					}
				}else{
					if (DataManager.getTicketManager(self).isTicketArchived(ticket)){
						DataManager.getTicketManager(self).unarchiverTicket(ticket);
						rating.setVisibility(View.GONE);
					}
				}
			}
			
		});
				
		//Bouton previous
		Button previous = (Button) this.findViewById(R.id.td_previous);
		previous.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				flipper.setInAnimation(AnimationUtils.loadAnimation(self,R.anim.push_right_in));  
	            flipper.setOutAnimation(AnimationUtils.loadAnimation(self,R.anim.push_right_out));  
	            getPreviousTicket();
			}
			
		});
		
		//Bouton previous
		Button next = (Button) this.findViewById(R.id.td_next);
		next.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				flipper.setInAnimation(AnimationUtils.loadAnimation(self,R.anim.push_left_in));  
	            flipper.setOutAnimation(AnimationUtils.loadAnimation(self,R.anim.push_left_out));  
	            getNextTicket();
			}
			
		});
		
		
		//Obtenir ticket qui vient de l'activite precedent
		ticket = (TicketItem) this.getIntent().getExtras().getSerializable("ticket");
		rating.setVisibility(DataManager.getTicketManager(self).isTicketArchived(ticket)?View.VISIBLE:View.GONE);
		setContent(ticket);
		setComposant();
	}
	

	private void setComposant() {
		Button btShare=(Button)findViewById(R.id.td_share);
		btShare.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				/*Intent i = new Intent();
				
				i.setClass(TicketDisplay.this, Share.class);
				Bundle bData = new Bundle();
				
				bData.putString("title", ticket.getTitle());
				bData.putString("link", ticket.getLink());
				i.putExtras( bData );
				TicketDisplay.this.startActivity(i);*/

				 Intent sendIntent = new Intent(Intent.ACTION_SEND);  
                 // Write the body of theEmail  
                 String emailBody =  "Title : \""+ticket.getTitle()+"\"\n"+"Link : "+ticket.getContent();
                 // Add attributes to the intent  
                 sendIntent.setType("text/plain"); // use this line for testing  
                                               // in the emulator  
                 //sendIntent.setType("message/rfc822"); // use this line for testing   
                                                   // on the real phone  
                // sendIntent.putExtra(Intent.EXTRA_EMAIL, mailto);  
                 sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Share the article"+ticket.getTitle());  
                 sendIntent.putExtra(Intent.EXTRA_TEXT, emailBody);  
                 startActivity(Intent.createChooser(sendIntent, "Email"));
			}
		});
		
	}


	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}
	
	@Override 
    public boolean onTouchEvent(MotionEvent event) { 
		return this.detector.onTouchEvent(event); 
    }  

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
         if (e1.getX() - e2.getX() > 120) {  
             this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.push_left_in));  
             this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.push_left_out));  
             getNextTicket();
             return true;  
         } else if (e1.getX() - e2.getX() < -120) {  
             this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.push_right_in));  
             this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.push_right_out));  
             getPreviousTicket();
             return true;  
         }  
         return true;  
	}
	
	/**
	 * Chercher le ticket suivant
	 */
	private void getNextTicket(){
		TicketItem tmp = DataManager.getTicketManager(this).getNextTicket(ticket);
		if (tmp!=null){
			ticket = tmp;
			setContent(ticket);
		}
		this.flipper.showNext();  
	}
	
	/**
	 * Cherche le ticket precedent
	 */
	private void getPreviousTicket(){
		TicketItem tmp = DataManager.getTicketManager(this).getPreviousTicket(ticket);
		if (tmp!=null){
			ticket = tmp;
			setContent(ticket);
		}
		this.flipper.showPrevious(); 
	}
	
	/**
	 * Mettre en place les contenues du ticket
	 * @param ti
	 */
	private void setContent(TicketItem ti){
		//Mettre a jour le statue isReaded
		if (!ti.isReaded()){
			ti.setReaded(true);
			if (DataManager.getTicketManager(this).isTicketArchived(ti)){
				DataManager.getTicketManager(this).updateTicket(ti);
			}
		}
				
		//Titre
		TextView title = (TextView) this.findViewById(R.id.td_title);
		title.setText(ti.getTitle());
		
		//Source, auteur, date
		TextView info = (TextView) this.findViewById(R.id.td_info_ticket);
		StringBuilder sb = new StringBuilder();
		if (!ti.getSource().equals("")) sb.append(ti.getSource());
		if (!ti.getAuthor().equals("")&&ti.getAuthor()!=null){
			if(sb.length()>0)
				sb.append(" - "+ti.getAuthor());
			else
				sb.append(ti.getAuthor());
		}
		if (!ti.getDate().equals("")&&ti.getDate()!=null){
			if(sb.length()>0)
				sb.append(" - "+ti.getDate());
			else
				sb.append(ti.getDate());
		}
		info.setText(sb.toString());
		
		//Description
		TextView content = (TextView) this.findViewById(R.id.td_content);
		content.setText(Html.fromHtml(ti.getContent(),new RemoteImageGetter(),null));
		
		//Link
		TextView link = (TextView) this.findViewById(R.id.td_hyperlink);
		link.setText(ti.getLink());
		
		//Archiver
		archiver.setChecked(DataManager.getTicketManager(this).isTicketArchived(ti));
		
		//Rating
		rating.setVisibility(DataManager.getTicketManager(self).isTicketArchived(ticket)?View.VISIBLE:View.GONE);
		
		rating.setRating(DataManager.getTicketManager(this).getRating(ti));
		
	}

}
